<template>
  <div>
    <!-- 尾部 -->
    <div class="footer">
      <div class="footer-outer">
        <div class="footer-outer-one">
          <div class="footer-outer-outer">
            <div class="footer-one-left">
              <a href=""><span>发布新帖</span></a>
              <a href=""><span>发布投票</span></a>
            </div>
            <div class="footer-one-right">
              <span>发贴请遵守</span>
              <span>贴吧协议及“七条底线” </span>
              <span>贴吧协议及“七条底线” </span>
            </div>
          </div>
        </div>
        <div class="footer-outer-two">
          <div style="width: 640px">
            <el-input v-model="input" placeholder="请输入标题" />
          </div>
          <div class="footer-outer-two-icon"></div>
        </div>
        <div style="border: 1px solid #ccc" class="warp_edit">
          <Toolbar
            style="border: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="min-height: 300px; overflow-y: hidden"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
          <el-button type="info" size="small" @click="sub">发布</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";
export default defineComponent({
  name: "TiebaComment",
});
</script>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onUpdated} from "vue";
import {useRouter} from "vue-router"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { useUserStore } from "@/stores/user";
import {
  DomEditor,
  type IDomEditor,
  type IEditorConfig,
} from "@wangeditor/editor";
import bar from "@/api/bar";
import _ from "@/utils/local";

const router = useRouter()
const store = useUserStore();

type InsertFnType = (url: string, alt: string, href: string) => void;

const mode = ref("simple");

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");
// 工具栏配置
const toolbarConfig = {
  toolbarKeys: [
    "insertImage",
    "|",
    "editImage",
    "|",
    "emotion",
    "|",
    "uploadImage",
  ],
  modalAppendToBody: true,
};
// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请输入内容...",
  scroll: false,
  MENU_CONF: {},
};

//  图片上传的配置
editorConfig.MENU_CONF!["uploadImage"] = {
  server: import.meta.env.VITE_APP_API + "/upload/image",

  fieldName: "image",

  // 单个文件的最大体积限制，默认为 2M
  maxFileSize: 1 * 1024 * 1024, // 1M

  // 最多可上传几个文件，默认为 100
  maxNumberOfFiles: 10,

  // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
  allowedFileTypes: [],

  // 自定义增加 http  header
  headers: {
    Authorization: "Bearer " + store.token,
  },

  // 超时时间，默认为 10 秒
  timeout: 5 * 1000, // 5 秒

  // 自定义插入图片
  customInsert(res: any, insertFn: InsertFnType) {
    // TS 语法
    // customInsert(res, insertFn) {                  // JS 语法
    // res 即服务端的返回结果
    const url = res.data.url;
    const alt = res.data.filename;
    const href = "";
    // 从 res 中找到 url alt href ，然后插入图片
    insertFn(url, alt, href);
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // 查询编辑器注册的所有菜单 key （可能有的不在工具栏上）
  // console.log(editor.getAllMenuKeys());
};

onUpdated(() => {
  const toolbar = DomEditor.getToolbar(editorRef.value);
  const curToolbarConfig = toolbar?.getConfig();
  // console.log(curToolbarConfig?.toolbarKeys, "curToolbarConfig?.toolbarKeys");
});

// 插入图片时获取已上传的图片列表
let UploadImageList: any = [];
editorConfig.MENU_CONF!["insertImage"] = {
  onInsertedImage(imageNode: any | null) {
    if (imageNode == null) return;

    UploadImageList.push({ url: imageNode.src, filename: imageNode.alt });
  },
};

// 提交 按钮
const input = ref("");

const sub = async () => {
  // 标题
  const title = input.value.trim();
  // 内容
  const description = editorRef.value.getText();
  // 图片列表
  const imageList = editorRef.value.getElemsByType("image").map((item: any) => {
    return { url: item.src, filename: item.alt };
  });
  // 合并参数
  const param = {
    title,
    description,
    user: store.userInfo._id,
    bar: JSON.parse(_.getItem("barInfo"))._id,
    imageList,
  };

  if (!title) {
    return ElMessage.error("请输入标题");
  }
  if (description || imageList) {
    try {
      await bar.requestCreateDynamic(param);
      ElMessage.success("发布成功")
      // 清空表单
      editorRef.value.setHtml('')
      input.value = ''
      router.go(0);
    } catch (e:any) {
      ElMessage.error(e);
    }
  }
};
</script>

<style lang="scss" scoped>
.warp_edit {
  margin-top: 19px;
  width: 640px;
  text-align: left;
  :deep(.w-e-image-container) img {
    width: 200px;
    height: 150px;
  }
}
.el-button {
  margin-left: 50%;
  transform: translateX(-50%);
}
.footer {
  padding-top: 20px;
  background-color: #f9f9f9;

  .footer-outer {
    margin-left: 20px;
    height: 441px;

    .footer-outer-one {
      .footer-outer-outer {
        width: 720px;
        overflow: hidden;

        .footer-one-left {
          float: left;
        }

        .footer-one-right {
          float: right;
          display: flex;
        }
      }
    }

    .footer-outer-two {
      display: flex;

      .footer-outer-two-icon {
        display: inline-block;
        width: 48px;
        height: 20px;
        cursor: pointer;
        background: url(//tb2.bdstatic.com/tb/img/poster/icon_topic_n_d25f560.png)
          no-repeat;
        position: relative;
        top: 5px;
        margin-left: 3px;
      }
    }

    .footer-outer-three {
      .footer-outer-three-nav {
        display: flex;
        padding: 12px 0;

        .footer-outer-three-nav-one {
          width: 48px;
          height: 20px;
          margin: 0;
          padding: 0;
          background: url(//tb2.bdstatic.com/tb/img/icon_png8_old_b8f2ed8.png)
            no-repeat;
          cursor: pointer;
        }

        .footer-outer-three-nav-three {
          width: 48px;
          height: 20px;
          margin: 0;
          padding: 0;
          background: url(//tb2.bdstatic.com/tb/img/icon_png8_old_b8f2ed8.png)
            no-repeat;
          cursor: pointer;
        }

        .footer-outer-three-nav-four {
          width: 48px;
          height: 20px;
          margin: 0;
          padding: 0;
          background: url(//tb2.bdstatic.com/tb/img/icon_png8_old_b8f2ed8.png)
            no-repeat;
          cursor: pointer;
        }

        .footer-outer-three-nav-five {
          width: 48px;
          height: 20px;
          margin: 0;
          padding: 0;
          background: url(//tb2.bdstatic.com/tb/img/icon_png8_old_b8f2ed8.png)
            no-repeat;
          cursor: pointer;
        }

        .footer-outer-three-nav-six {
          width: 48px;
          height: 20px;
          margin: 0;
          padding: 0;
          background: url(//tb2.bdstatic.com/tb/img/icon_png8_old_b8f2ed8.png)
            no-repeat;
          cursor: pointer;
        }

        .footer-outer-three-nav-seven {
          width: 48px;
          height: 20px;
          margin: 0;
          padding: 0;
          background: url(//tb2.bdstatic.com/tb/img/icon_png8_old_b8f2ed8.png)
            no-repeat;
          cursor: pointer;
        }
      }

      .footer-outer-three-nav-last {
        background: url(//tb2.bdstatic.com/tb/img/icon_fullscreen_max_6daeb71.png)
          no-repeat;
      }
    }
  }
}
</style>
